"""
AI工具详情数据模型
"""

from datetime import datetime
from typing import List, Optional, Dict, Any

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class ToolParameter(BaseModel):
    """工具参数模型"""
    param_name: str = Field(..., description="参数名称")
    param_type: str = Field(..., description="参数类型，如integer、float、string、boolean等")
    description: str = Field(default="", description="参数描述")
    default_value: Any = Field(None, description="默认值")
    is_required: bool = Field(default=False, description="是否必需参数")


class AIWebDetailTools(BaseModel):
    """AI工具详情实体类"""
    id: Optional[int] = Field(None, description="工具ID")
    parent_id: int = Field(..., description="关联的工具集ID")
    tool_type: int = Field(..., description="工具类型（1=基础工具,2=MCP工具）")
    tool_name: str = Field(..., max_length=100, description="工具名称")
    server_code: Optional[str] = Field(None, max_length=100,
                                       description="服务代码（基础工具存储category_code，MCP工具存储mcp_name）")
    description: Optional[str] = Field(None, description="工具描述")
    is_enabled: bool = Field(default=True, description="是否启用")
    human_interactive_flag: int = Field(default=0, description="人工交互标识（0=不需要人工交互,1=需要人工交互）")
    parameters: List[Dict[str, Any]] = Field(default_factory=list, description="工具参数配置")
    created_at: Optional[datetime] = Field(None, description="创建时间")
    updated_at: Optional[datetime] = Field(None, description="更新时间")

    model_config = ConfigDict(from_attributes=True)

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    @field_validator('tool_type', mode='before')
    @classmethod
    def validate_tool_type(cls, v):
        """验证工具类型"""
        if v not in [1, 2]:
            raise ValueError('工具类型必须是1（基础工具）或2（MCP工具）')
        return v

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v

    @field_validator('tool_name')
    @classmethod
    def validate_tool_name(cls, v):
        """验证工具名称"""
        if not v or not v.strip():
            raise ValueError('工具名称不能为空')
        if len(v.strip()) > 100:
            raise ValueError('工具名称长度不能超过100个字符')
        return v.strip()

    @field_validator('server_code')
    @classmethod
    def validate_server_code(cls, v):
        """验证服务代码"""
        if v is not None:
            if not v.strip():
                return None  # 空字符串转为None
            if len(v.strip()) > 100:
                raise ValueError('服务代码长度不能超过100个字符')
            return v.strip()
        return v

    def get_tool_type_display(self) -> str:
        """获取工具类型显示文本"""
        return "基础工具" if self.tool_type == 1 else "MCP工具"

    def get_human_interactive_display(self) -> str:
        """获取人工交互标识显示文本"""
        return "需要交互" if self.human_interactive_flag == 1 else "无需交互"

    def is_base_tool(self) -> bool:
        """判断是否为基础工具"""
        return self.tool_type == 1

    def is_mcp_tool(self) -> bool:
        """判断是否为MCP工具"""
        return self.tool_type == 2

    def need_human_interaction(self) -> bool:
        """判断是否需要人工交互"""
        return self.human_interactive_flag == 1


class AIWebDetailToolsCreate(BaseModel):
    """创建工具详情请求模型"""
    parent_id: int = Field(..., description="关联的工具集ID")
    tool_type: int = Field(..., description="工具类型（1=基础工具,2=MCP工具）")
    tool_name: str = Field(..., max_length=100, description="工具名称")
    server_code: Optional[str] = Field(None, max_length=100,
                                       description="服务代码（基础工具存储category_code，MCP工具存储mcp_name）")
    description: Optional[str] = Field(None, description="工具描述")
    is_enabled: bool = Field(default=True, description="是否启用")
    human_interactive_flag: int = Field(default=0, description="人工交互标识（0=不需要人工交互,1=需要人工交互）")
    parameters: List[Dict[str, Any]] = Field(default_factory=list, description="工具参数配置")

    @field_validator('tool_type', mode='before')
    @classmethod
    def validate_tool_type(cls, v):
        """验证工具类型"""
        if v not in [1, 2]:
            raise ValueError('工具类型必须是1（基础工具）或2（MCP工具）')
        return v

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v

    @field_validator('tool_name')
    @classmethod
    def validate_tool_name(cls, v):
        """验证工具名称"""
        if not v or not v.strip():
            raise ValueError('工具名称不能为空')
        if len(v.strip()) > 100:
            raise ValueError('工具名称长度不能超过100个字符')
        return v.strip()

    @field_validator('server_code')
    @classmethod
    def validate_server_code(cls, v):
        """验证服务代码"""
        if v is not None:
            if not v.strip():
                return None  # 空字符串转为None
            if len(v.strip()) > 100:
                raise ValueError('服务代码长度不能超过100个字符')
            return v.strip()
        return v


class AIWebDetailToolsUpdate(BaseModel):
    """更新工具详情请求模型"""
    tool_type: Optional[int] = Field(None, description="工具类型（1=基础工具,2=MCP工具）")
    tool_name: Optional[str] = Field(None, max_length=100, description="工具名称")
    server_code: Optional[str] = Field(None, max_length=100,
                                       description="服务代码（基础工具存储category_code，MCP工具存储mcp_name）")
    description: Optional[str] = Field(None, description="工具描述")
    is_enabled: Optional[bool] = Field(None, description="是否启用")
    human_interactive_flag: Optional[int] = Field(None, description="人工交互标识（0=不需要人工交互,1=需要人工交互）")
    parameters: Optional[List[Dict[str, Any]]] = Field(None, description="工具参数配置")

    @field_validator('tool_type', mode='before')
    @classmethod
    def validate_tool_type(cls, v):
        """验证工具类型"""
        if v is not None and v not in [1, 2]:
            raise ValueError('工具类型必须是1（基础工具）或2（MCP工具）')
        return v

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v is not None and v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v

    @field_validator('tool_name')
    @classmethod
    def validate_tool_name(cls, v):
        """验证工具名称"""
        if v is not None:
            if not v or not v.strip():
                raise ValueError('工具名称不能为空')
            if len(v.strip()) > 100:
                raise ValueError('工具名称长度不能超过100个字符')
            return v.strip()
        return v

    @field_validator('server_code')
    @classmethod
    def validate_server_code(cls, v):
        """验证服务代码"""
        if v is not None:
            if not v.strip():
                return None  # 空字符串转为None
            if len(v.strip()) > 100:
                raise ValueError('服务代码长度不能超过100个字符')
            return v.strip()
        return v


class AIWebDetailToolsResponse(BaseModel):
    """工具详情响应模型"""
    id: int
    parent_id: int
    tool_type: int
    tool_name: str
    server_code: Optional[str]
    description: Optional[str]
    is_enabled: bool
    human_interactive_flag: int
    parameters: List[Dict[str, Any]]
    created_at: datetime
    updated_at: datetime

    # 额外的显示字段
    tool_type_display: Optional[str] = None
    human_interactive_display: Optional[str] = None

    model_config = ConfigDict(from_attributes=True)

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    @field_validator('tool_type_display', mode='before')
    @classmethod
    def set_tool_type_display(cls, v, info):
        """设置工具类型显示文本"""
        if hasattr(info, 'data') and 'tool_type' in info.data:
            return "基础工具" if info.data['tool_type'] == 1 else "MCP工具"
        return v

    @field_validator('human_interactive_display', mode='before')
    @classmethod
    def set_human_interactive_display(cls, v, info):
        """设置人工交互标识显示文本"""
        if hasattr(info, 'data') and 'human_interactive_flag' in info.data:
            return "需要交互" if info.data['human_interactive_flag'] == 1 else "无需交互"
        return v


class AIWebDetailToolsListResponse(BaseModel):
    """工具详情列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[AIWebDetailToolsResponse] = Field(..., description="工具详情列表")


class AIWebDetailToolsQueryParams(BaseModel):
    """工具详情查询参数"""
    parent_id: Optional[int] = Field(None, description="工具集ID筛选")
    tool_type: Optional[int] = Field(None, description="工具类型筛选（1=基础工具,2=MCP工具）")
    tool_name: Optional[str] = Field(None, description="工具名称模糊查询")
    server_code: Optional[str] = Field(None, description="服务代码筛选")
    is_enabled: Optional[bool] = Field(None, description="状态筛选")
    human_interactive_flag: Optional[int] = Field(None, description="人工交互标识筛选（0=不需要,1=需要）")

    @field_validator('tool_type', mode='before')
    @classmethod
    def validate_tool_type(cls, v):
        """验证工具类型"""
        if v is not None and v not in [1, 2]:
            raise ValueError('工具类型必须是1（基础工具）或2（MCP工具）')
        return v

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v is not None and v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v


class AIWebDetailToolsStatusUpdate(BaseModel):
    """工具详情状态更新模型"""
    is_enabled: bool = Field(..., description="新状态")


class AIWebDetailToolsInteractiveUpdate(BaseModel):
    """工具详情人工交互标识更新模型"""
    human_interactive_flag: int = Field(..., description="人工交互标识（0=不需要人工交互,1=需要人工交互）")

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v


class SingleToolModel(BaseModel):
    """单个工具配置模型"""
    id: Optional[int] = Field(None, description="工具ID")
    tool_name: str = Field(..., description="工具名称")
    server_code: Optional[str] = Field(None, description="服务代码")
    description: str = Field(default="", description="工具描述")
    is_enabled: bool = Field(default=True, description="是否启用")
    human_interactive_flag: int = Field(default=0, description="人工交互标识（0=不需要人工交互,1=需要人工交互）")
    parameters: List[ToolParameter] = Field(default_factory=list, description="工具参数列表")

    @field_validator('tool_name')
    @classmethod
    def validate_tool_name(cls, v):
        """验证工具名称"""
        if not v or not v.strip():
            raise ValueError('工具名称不能为空')
        return v.strip()

    @field_validator('server_code')
    @classmethod
    def validate_server_code(cls, v):
        """验证服务代码"""
        if v is not None:
            if not v.strip():
                return None  # 空字符串转为None
            return v.strip()
        return v

    @field_validator('human_interactive_flag', mode='before')
    @classmethod
    def validate_human_interactive_flag(cls, v):
        """验证人工交互标识"""
        if v not in [0, 1]:
            raise ValueError('人工交互标识必须是0（不需要）或1（需要）')
        return v
